import { ref } from 'vue'
import { getMoHuList } from '@renderer/api/mohu'
import _ from 'lodash'

export default () => {
    const loading = ref(false)
    const showDetail = ref(false)
    const imgLists = ref<any>([])
    const Imgs = ref<HTMLElement | null>(null)
    const showIndex = ref(0)
    const typeChild = ref<any>([])
    const activeTypeIndex = ref(0)
    const activeDetailType = ref('img1')
    const allTypes = ref<any>(null)
    const detailTypes = ref<any>(null)
    const imgSet = new Set()

    const getImgList = async (type: string) => {
        loading.value = true
        const obj = {
            return: 'json',
            id: type,
            num: 20,
            random: Math.random(),
            size: 'mw1024'
        }
        const res = await getMoHuList(obj)
        if (res.pic) res.pic.forEach(el => {
            // 通过 imgSet 判断是否已经存在
            if (imgSet.has(el)) return
            const obj = {
                src: el,
                source: el.replace('mw1024', 'large'),
                title: ''
            }
            imgSet.add(el)
            imgLists.value.push(obj)
        })
        loading.value = false
    }

    const scrollEvent = _.debounce(() => {
        // 计算滚动条距离底部的距离
        const scrollBottom = Imgs.value?.scrollHeight! - Imgs.value?.scrollTop! - Imgs.value?.clientHeight!
        if (scrollBottom < 200) {
            getImgList(activeDetailType.value)
        }
    }, 500)

    const viewPicture = (num: number) => {
        showIndex.value = num
        showDetail.value = true
    }
    const closePicture = () => {
        showDetail.value = false
    }
    const selectChild = (child: any, num: number) => {
        activeTypeIndex.value = num
        typeChild.value = child
        detailTypes.value.style.left = '0'
        allTypes.value.style.left = '-120px'
    }
    const selectType = (type: string) => {
        if (type == activeDetailType.value) return
        activeDetailType.value = type
        imgLists.value = []
        getImgList(type)
    }
    const backAllTypes = () => {
        detailTypes.value.style.left = '100%'
        allTypes.value.style.left = '0'
    }
    return {
        loading,
        showDetail,
        Imgs,
        imgLists,
        allTypes,
        detailTypes,
        showIndex,
        typeChild,
        activeTypeIndex,
        activeDetailType,
        getImgList,
        scrollEvent,
        viewPicture,
        closePicture,
        selectChild,
        selectType,
        backAllTypes
    }
}